﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Net.Mail;
using System.Configuration;
using TimKen.DataEntity;
using System.Web;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using System.Collections;
using TimKen.BussLogic;
using System.Data;



namespace TimKen.App
{
    /// <summary>
    /// 工具类，如发邮件
    /// </summary>
    public class Tools
    {
        public static void SendEmail(MailMessage mm)
        {
            try
            {
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
                string address = ConfigurationManager.AppSettings["MailAddress"];
                string mailAccount = ConfigurationManager.AppSettings["MailAccount"];
                string mailSendAddr = ConfigurationManager.AppSettings["MailSendAddr"];//发件人
                string PWD = ConfigurationManager.AppSettings["Password"];
                string host, port;
                if (address.Contains(":"))
                {
                    host = address.Split(':')[0];
                    port = address.Split(':')[1];
                    sc.Port = Int32.Parse(port);
                }
                else
                {
                    host = address;
                }
                sc.Host = host;
                sc.Credentials = new System.Net.NetworkCredential(mailAccount, PWD);
                MailAddress from = new MailAddress(mailSendAddr);//修改发件人地址
                mm.From = from;
                sc.Send(mm);
            }
            catch (Exception e1)
            {
                throw new CstmException(e1.Message);
            }
        }
        public static string EncryptUserName(string username)
        {
            string sKey = "0I9E5A1F";
            byte[] data = Encoding.UTF8.GetBytes(username);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream(); //创建其支持存储区为内存的流。 
            CryptoStream cs = new CryptoStream(ms, DES.CreateEncryptor(), CryptoStreamMode.Write);//将数据流连接到加密转换流 
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock(); //用缓冲区的当前状态更新基础数据源或储存库，随后清除缓 
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2} ", b);
            }
            return ret.ToString().Replace(" ", "");

        }
        public static string DecryptUserName(string enUserName)
        {
            string sKey = "0I9E5A1F";
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            //Put the input string into the byte array 
            byte[] inputByteArray = new byte[enUserName.Length / 2];
            for (int x = 0; x < enUserName.Length; x += 2)
            {
                int i = Convert.ToInt32(enUserName.Substring(x, 2), 16);
                inputByteArray[x / 2] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            //Flush the data through the crypto stream into the memory stream 
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            //Get the decrypted data back from the memory stream 
            //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象 
            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.UTF8.GetString(ms.ToArray());

        }
        public static bool CheckFrozen(bool Frozen, object FrozenFrom, object FrozenTo)
        {
            bool IsFrozen = true;
            if (Frozen)
            {
                if (FrozenFrom != null && FrozenFrom.ToString() != "")
                {
                    DateTime freezeFrom = Convert.ToDateTime(FrozenFrom);
                    if (freezeFrom > DateTime.Now)
                    {
                        IsFrozen = false;
                    }
                }
                if (FrozenTo != null && FrozenTo.ToString() != "")
                {
                    DateTime freezeTo = Convert.ToDateTime(FrozenTo);
                    if (freezeTo < DateTime.Now)
                    {
                        IsFrozen = false;
                    }
                }
            }
            else
            {
                IsFrozen = false;
            }
            return IsFrozen;
        }


        public static string Encrypt(string pToEncrypt)
        {
            string sKey = "0I9E5A1F";
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 

            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            //byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt); 

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 
            MemoryStream ms = new MemoryStream(); //使得输入密码必须输入英文文本
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        /**/
        /// 
        /// DEC 解密过程
        /// 
        /// 
        /// 
        /// 
        public static string Decrypt(string pToDecrypt)
        {
            string sKey = "0I9E5A1F";
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量，此值重要，不能修改 
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder(); //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象 

            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }

        #region 下载文件
        /// <summary> 
        /// 下载文件 
        /// </summary> 
        /// <param name="fileName">文件路径</param> 
        /// <returns></returns> 
        public static void FileDownLoad(System.Web.UI.Page page, string filepath)
        {
            FileInfo DownloadFile = new FileInfo(filepath); //设置要下载的文件 
            page.Response.Clear(); //清除缓冲区流中的所有内容输出 
            page.Response.ClearHeaders(); //清除缓冲区流中的所有头 
            page.Response.Buffer = false; //设置缓冲输出为false 
            //设置输出流的 HTTP MIME 类型为application/octet-stream 
            page.Response.ContentType = "application/octet-stream";
            //将 HTTP 头添加到输出流 
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
            page.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            //将指定的文件直接写入 HTTP 内容输出流。 
            page.Response.WriteFile(DownloadFile.FullName);
            page.Response.Flush(); //向客户端发送当前所有缓冲的输出 
            page.Response.End(); //将当前所有缓冲的输出发送到客户端 
        }

        #endregion




        public static VelocityEngine InitVelocity()
        {
            //创建NVelocity引擎的实例对象
            VelocityEngine velocity = new VelocityEngine();
            //初始化该实例对象
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.HttpContext.Current.Server.MapPath("\\mailTemplate"));
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
            velocity.Init(props);

            return velocity;
        }

        public static void SendOrderConfirmdEmail(string OrderID)
        {
            OrderManager orderManager = new OrderManager();
            Order order = orderManager.GetModel(OrderID);

            TimKen.BussLogic.OrderItemManager orderItemM = new TimKen.BussLogic.OrderItemManager();
            order.OrderItems = orderItemM.GetOrderItemList(OrderID);

            CustomerManager customerManager = new CustomerManager();
            Customer customer = customerManager.GetModel(order.CustomerID);

            UserAccountManager uam = new UserAccountManager();
            UserAccount user = uam.GetModel(order.Creator);


            if (string.IsNullOrEmpty(user.Email))
                return;

            TransTypeManager tm = new TransTypeManager();
            string shipTypeNameCn = tm.GetModel(order.ShipType.Value, 1).TransTypeName;
            string shipTypeNameEn = tm.GetModel(order.ShipType.Value, 2).TransTypeName;


            VelocityEngine velocity = InitVelocity();
            //从文件中读取模板
            Template temp = velocity.GetTemplate("ConfirmOrderMail.vm");

            IContext context = new VelocityContext();
            context.Put("customer", customer);
            context.Put("order", order);
            context.Put("shipTypeNameCn", shipTypeNameCn);
            context.Put("shipTypeNameEn", shipTypeNameEn);

            string TimKenUrl = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];

            string encryOrderID = Tools.EncryptUserName(OrderID);
            context.Put("host", TimKenUrl);
            context.Put("orderId", encryOrderID);


            //合并模板
            StringWriter writer = new StringWriter();
            temp.Merge(context, writer);



            //发送邮件
            MailMessage mm = new MailMessage();
            mm.Subject = string.Format("您在驿桥的订单({0}) -- 订单已经确认", order.OrderNo);
            mm.IsBodyHtml = true;
            mm.To.Add(user.Email);
            mm.Body = writer.GetStringBuilder().ToString();
            SendEmail(mm);
        }


        public static void SendOrderCreateEmail(string OrderID)
        {
            OrderManager orderManager = new OrderManager();
            Order order = orderManager.GetModel(OrderID);

            TimKen.BussLogic.OrderItemManager orderItemM = new TimKen.BussLogic.OrderItemManager();
            order.OrderItems = orderItemM.GetOrderItemList(OrderID);

            CustomerManager customerManager = new CustomerManager();
            Customer customer = customerManager.GetModel(order.CustomerID);

 

            TransTypeManager tm = new TransTypeManager();
            string shipTypeNameCn = tm.GetModel(order.ShipType.Value, 1).TransTypeName;



            VelocityEngine velocity = InitVelocity();
            //从文件中读取模板
            Template temp = velocity.GetTemplate("CreateOrderMail.vm");

            IContext context = new VelocityContext();
            context.Put("customer", customer);
            context.Put("order", order);
            context.Put("shipTypeName", shipTypeNameCn);

          


            //合并模板
            StringWriter writer = new StringWriter();
            temp.Merge(context, writer);



            //发送邮件
            MailMessage mm = new MailMessage();
            mm.Subject = string.Format("驿桥EC订单通知({0}) -- 订单已经建立", order.OrderNo);
            mm.IsBodyHtml = true;


            string tos = ConfigurationManager.AppSettings["CreateOrderNotifyEmail"];
            mm.To.Add(tos);


            mm.Body = writer.GetStringBuilder().ToString();
            SendEmail(mm);

        }



        public static void SendApplyForCustomerEmail(string username)
        {

            string tos = ConfigurationManager.AppSettings["ApplyCustomerNotifyEmail"];

            if (string.IsNullOrEmpty(tos))
                return;

            WebUserManager wm = new WebUserManager();
            WebUser user = wm.GetModel(username);

            VelocityEngine velocity = InitVelocity();
            //从文件中读取模板
            Template temp = velocity.GetTemplate("ApplyCustomerMail.vm");

            IContext context = new VelocityContext();
            context.Put("user", user);


            //合并模板
            StringWriter writer = new StringWriter();
            temp.Merge(context, writer);


            //发送邮件
            MailMessage mm = new MailMessage();
            mm.Subject = "驿桥EC用户注册通知";
            mm.IsBodyHtml = true;
            mm.To.Add(tos);
            mm.Body = writer.GetStringBuilder().ToString();
            SendEmail(mm);
        }



        public static void SendCreateCustomerEmail(string username)
        {

            UserAccountManager uam = new UserAccountManager();
            UserAccount user = uam.GetModel(username);
            CustomerManager cm = new CustomerManager();
            Customer customer = cm.GetModel(user.CustomerID.Value);

            if (string.IsNullOrEmpty(user.Email))
                return;

            VelocityEngine velocity = InitVelocity();

            //从文件中读取模板
            Template temp = velocity.GetTemplate("CreateCustomerMail.vm");

            IContext context = new VelocityContext();
            context.Put("user", user);
            context.Put("customer", customer);

            //合并模板
            StringWriter writer = new StringWriter();
            temp.Merge(context, writer);


            //发送邮件
            MailMessage mm = new MailMessage();
            mm.Subject = "驿桥EC网络买家帐号审核通过";
            mm.IsBodyHtml = true;
            mm.To.Add(user.Email);
            mm.Body = writer.GetStringBuilder().ToString();
            SendEmail(mm);
        }



        public static void SendOrderConfirmPayment(string OrderID)
        {
            OrderManager orderManager = new OrderManager();
            Order order = orderManager.GetModel(OrderID);
 
            //发送邮件
            MailMessage mm = new MailMessage();
            mm.Subject = string.Format("驿桥EC订单通知({0}) -- 客户已经确认，请登录后台确认付款", order.OrderNo);
            mm.IsBodyHtml = true;


            string tos = ConfigurationManager.AppSettings["CreateOrderNotifyEmail"];
            mm.To.Add(tos);


            mm.Body = mm.Subject;
            SendEmail(mm);

        }

        public static string  GetDefualtOrderTerm()
        {


            VelocityEngine velocity = InitVelocity();
            //从文件中读取模板
            Template temp = velocity.GetTemplate("DefaultOrderTerm.vm");

            IContext context = new VelocityContext();

            //合并模板
            StringWriter writer = new StringWriter();
            temp.Merge(context, writer);
            return writer.GetStringBuilder().ToString();
        }
    }
}